package com.sc.javaee.service.impl;

import com.sc.javaee.mapper.EnterpriseMapper;
import com.sc.javaee.mapper.UserEnterpriseMapper;
import com.sc.javaee.pojo.Enterprise;
import com.sc.javaee.service.enterpriseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class enterpriseServiceImpl implements enterpriseService {
    @Autowired
    EnterpriseMapper enterpriseMapper;
    @Autowired
    UserEnterpriseMapper userEnterpriseMapper;
    @Override
    public List<Enterprise> getAllEnterprises() {
        return enterpriseMapper.selectAll();
    }

    @Override
    public List<Enterprise> searchEnterprises(String keyword) {
        return enterpriseMapper.searchByName(keyword);
    }

    @Override
    public boolean bindUserToEnterprise(Integer userId, Integer enterpriseId) {
        // 检查是否已绑定
        Integer existingBinding = userEnterpriseMapper.selectByUserId(userId);
        if (existingBinding != null) {
            // 已绑定，更新绑定
            return userEnterpriseMapper.updateUserEnterprise(userId, enterpriseId) > 0;
        } else {
            // 新绑定
            return userEnterpriseMapper.insertUserEnterprise(userId, enterpriseId) > 0;
        }
    }

    @Override
    public Enterprise getUserEnterprise(Integer userId) {
        Integer enterpriseId = userEnterpriseMapper.selectByUserId(userId);
        if (enterpriseId != null) {
            return enterpriseMapper.selectByPrimaryKey(enterpriseId);
        }
        return null;
    }
}
